package com.schoolMall.service.impl;

import com.github.pagehelper.PageHelper;
import com.schoolMall.dao.ProductDao;
import com.schoolMall.dao.ProductImgDao;
import com.schoolMall.domain.Product;
import com.schoolMall.domain.ProductImg;
import com.schoolMall.dto.ImageHolder;
import com.schoolMall.dto.ProductDto;
import com.schoolMall.enums.EnableStatusEnum;
import com.schoolMall.enums.ProductStateEnum;
import com.schoolMall.exception.ProductOperationException;
import com.schoolMall.service.ProductService;
import com.schoolMall.utils.ImgUtil;
import com.schoolMall.utils.PathUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author:zyh
 * @Time:2021-09-01-9:58
 * @email:1269231889@qq.com
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductImgDao productImgDao;

    private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Override
    @Transactional
    //1.处理图片
    //2.写入商品信息
    //3.批量处理商品详情图
    //4.批量插入商品详情图到库中
    public ProductDto addProduct(Product product, ImageHolder imageHolder, List<ImageHolder> imageHolderList) throws ProductOperationException {
        if (Objects.isNull(product)) {
            return new ProductDto(ProductStateEnum.NULL_PRODUCT);
        }
        if (Objects.isNull(product.getShop()) || Objects.isNull(product.getShop().getShopId())) {
            return new ProductDto(ProductStateEnum.NULL_SHOP);
        }
        product.setCreateTime(new Date());
        product.setLastEditTime(new Date());
        product.setEnableStatus(EnableStatusEnum.ENABLE.getVal());
        if (Objects.nonNull(imageHolder)) {
            try {
                addProductImgAddr(product, imageHolder);
            } catch (IOException e) {
                throw new ProductOperationException("保存图片失败");
            }
        }

        if (CollectionUtils.isNotEmpty(imageHolderList)) {
            addProductImg(product, imageHolderList);
        }
        int insertNum = 0;
        try {
            insertNum = productDao.insertProduct(product);
        } catch (Exception e) {
            throw new ProductOperationException("插入异常");
        }
        if (insertNum < 1) {
            throw new ProductOperationException("插入失败");
        }
        return new ProductDto(ProductStateEnum.SUCCESS, product);
    }

    @Override
    public Product queryProductById(long productId) {
        return productDao.queryProductById(productId);
    }

    @Override
    public ProductDto modifyProduct(Product product, ImageHolder holder, List<ImageHolder> imageHolderList) throws ProductOperationException {
        if (Objects.isNull(product) || Objects.isNull(product.getShop()) || product.getShop().getShopId() < 1) {
            return new ProductDto(ProductStateEnum.FAIL);
        }
        if (Objects.nonNull(holder)) {
            Product tempProduct = queryProductById(product.getProductId());
            try {
                if (Objects.nonNull(tempProduct.getImgAddr())) {
                    ImgUtil.deleteFileOrPath(tempProduct.getImgAddr());
                }
                addProductImgAddr(product, holder);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (CollectionUtils.isNotEmpty(imageHolderList)) {
            deleteProductImgList(product.getProductId());
            addProductImg(product, imageHolderList);
        }
        int updateNum = productDao.modifyProduct(product);
        logger.info("更新数为:{}", updateNum);
        if (updateNum < 1) {
            throw new ProductOperationException("更新失败");
        }
        return new ProductDto(ProductStateEnum.SUCCESS, product);
    }

    @Override
    public ProductDto getProductList(Product product, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productDao.queryProductList(product);
        logger.info("ProductService#getProductList:{}", products);

        ProductDto productDto = new ProductDto(ProductStateEnum.SUCCESS, products);
        productDto.setCount(products.size());
        return productDto;
    }

    private void deleteProductImgList(Long productId) {
        List<ProductImg> productImgList = productImgDao.queryProductImgList(productId);
        productImgList.stream().
                forEach(productImg -> ImgUtil.deleteFileOrPath(productImg.getImgAddr()));
        int effectNum = 0;
        try {
            effectNum = productImgDao.deleteProductImgByProductId(productId);
        } catch (Exception e) {
            throw new ProductOperationException("删除商品详情图片失败");
        }
        logger.info("删除商品有关图片列表:{}", effectNum);
    }

    private void addProductImgAddr(Product product, ImageHolder imageHolder) throws IOException {
        String shopImagePath = PathUtil.getShopImagePath(product.getShop().getShopId());
        String imgAddr = ImgUtil.generateThumbnail(imageHolder, shopImagePath);
        product.setImgAddr(imgAddr);
    }

    private void addProductImg(Product product, List<ImageHolder> imageHolderList) {
        String shopImagePath = PathUtil.getShopImagePath(product.getShop().getShopId());
        List<ProductImg> productImgList = new ArrayList<>();
        imageHolderList.stream().forEach(imageHolder -> {
            String imgAddr = null;
            try {
                imgAddr = ImgUtil.generateNomralImg(imageHolder, shopImagePath);
            } catch (IOException e) {
                throw new ProductOperationException("图片存放异常");
            }
            ProductImg productImg = new ProductImg();
            productImg.setProductId(product.getProductId());
            productImg.setImgAddr(imgAddr);
            productImg.setCreateTime(new Date());
            productImgList.add(productImg);
        });
        if (CollectionUtils.isNotEmpty(productImgList)) {
            int insertNum = 0;
            try {
                insertNum = productImgDao.batchInsertImg(productImgList);
                if (insertNum < 1) {
                    throw new ProductOperationException("创建商品详情图片失败");
                }
            } catch (Exception e) {
                throw new ProductOperationException("商品图片插入失败" + e.toString());
            }
        }
    }
}
